<template>
	<view class="box">
		<myNav :title="title" :height="65" :isBlack="true" />
		<view class="container pdl-30 pdr-30">
			<view class="top mgt-39">
				<view class="title fs42">请输入银行卡信息</view>
				<view class="small_desc fs22">为资金安全，请绑定本人银行卡</view>
			</view>
			<u-form class="mgt-56" :model="form" ref="formRef" :error-type="errorType" label-width="180"
				:label-style="formStyle">
				<u-form-item class="common_item pdl-19 pdr-25" label="卡号" prop="idcard" :border-bottom="false">
					<view class="flex-ac flex1">
						<u-input style="text-align: right;" type="number" v-model="form.idcard" placeholder="请输入卡号"
							clearable maxlength="24" showWordLimit />
						<image class="photo_icon pdl-24" src="/static/src/bank/photo.png"></image>
					</view>
				</u-form-item>
				<u-form-item class="common_item mgt-20 pdl-19 pdr-25" label="银行名称" prop="bankName">
					<view class="flex-ac flex1 idcard_input">
						<view @click="handleBank" class="mgr-12" :class="form.bankName?'':'default'">
							{{form.bankName?form.bankName:'请选择银行'}}
						</view>
						<view class="df mgt-5">
							<u-icon name="arrow-right" color="#CCCCCC" size="26"></u-icon>
						</view>
					</view>
				</u-form-item>
				<u-form-item class="common_item pdl-19 pdr-25" label="开户行名称" prop="openingBank">
					<view class="df flex1 idcard_input">
						<u-input style="text-align: right;" type="text" v-model="form.openingBank"
							placeholder="请输入开户行名称" clearable maxlength="120" showWordLimit />
					</view>
				</u-form-item>
				<u-form-item class="common_item pdl-19 pdr-25" label="持卡人姓名" prop="name">
					<view class="df flex1 idcard_input">
						<u-input style="text-align: right;" type="text" v-model="form.name" placeholder="请输入持卡人姓名"
							clearable maxlength="120" showWordLimit />
					</view>
				</u-form-item>
				<u-form-item class="common_item mgt-20 pdl-19 pdr-25" label="预留手机号" prop="tel">
					<view class="df flex1 idcard_input">
						<u-input style="text-align: right;" type="number" v-model="form.tel" placeholder="请输入预留手机号"
							clearable maxlength="11" showWordLimit />
					</view>
				</u-form-item>
				<!-- <u-form-item class="common_item pdl-19 pdr-25" label="验证码" prop="code">
					<u-input type="number" v-model="form.code" placeholder="请输入验证码" clearable maxlength="120"
						showWordLimit />
					<template v-slot:right>
						<text class="code_text" @click="handleCode">{{code}}</text>
					</template>
				</u-form-item> -->
			</u-form>
			<u-button @click="handleSure" class="sure_btn pdl-7 pdr-3 mgt-130" shape="circle" :ripple="true"
				type="primary" throttle-time="2000">确定</u-button>
		</view>
		<u-select :default-value="[getCurrentIndex]" v-model="showBank" :safe-area-inset-bottom="true"
			mode="single-column" :list="list" label-name="dictLabel" value-name="dictValue"
			@confirm="handConfim"></u-select>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, onUnmounted } from "vue";

	import { useInformation } from '@/store/modules/index.ts'

	import { addBank } from "@/api/bank";

	import { getDict } from "@/api/dict";

	import myNav from "../../components/myNav.vue"

	import type { FormData, ListItem, bankAddRules } from "../../static/src/types/bank"

	const user = useInformation()

	const title = ref("绑定银行卡")
	const formRef = ref<any>(null);
	const form = ref<FormData>({
		idcard: "",
		bankName: "",
		bankValue: "",
		openingBank: "",
		name: "",
		tel: user.phoneNumber || ""
		// code: ""
	})
	const formStyle = {
		color: '#333333',
		fontFamily: ' PingFang SC',
		fontWeight: '500',
		fontSize: '32rpx'
	}
	const errorType = ref(['message'])
	const showBank = ref<boolean>(false)
	const list = ref<ListItem[]>([]);
	const rules = ref<bankAddRules>({
		idcard: [{ required: true, message: "请输入卡号", trigger: ['change', 'blur'] }],
		bankName: [{ required: true, message: "请选择银行", trigger: ['change', 'blur'] }],
		openingBank: [{ required: true, message: "请输入开户行名称", trigger: ['change', 'blur'] }],
		name: [
			{ required: true, message: "请输入持卡人姓名", trigger: ['change', 'blur'] }, 
			{ pattern: /^[\u4E00-\u9FA5]+$/, message: "只能输入汉字" }
		],
		tel: [{ required: true, message: "请输入预留手机号", trigger: ['change', 'blur'] }]
	});
	const countdown = ref<number>(0);// 倒计时秒数
	const timer = ref<NodeJS.Timeout | null>(null);
	const bankIndex = ref<number>(0);

	const getCurrentIndex = computed(() => {
		return bankIndex.value;
	})
	const code = computed(() => {
		return countdown.value > 0 ? `${countdown.value}s` : '获取验证码'
	})

	const loadDictData = async () => {
		let res = await getDict('lo_bank_code')
		if (res) {
			list.value = res.data
		}
	}

	const handleBank = async () => {
		await loadDictData()
		showBank.value = true
	}

	const handConfim = async (e : any) => {
		form.value.bankName = e[0].label
		form.value.bankValue = e[0].value
		bankIndex.value = list.value.findIndex(item => item.dictValue === e[0].value);
	}
	const stopTimer = () => {
		if (timer.value) {
			clearInterval(timer.value)
			timer.value = null
		}
	}
	const startTimer = () => {
		// 清除已有定时器
		if (timer.value) {
			clearInterval(timer.value)
		}
		countdown.value = 60
		timer.value = setInterval(() => {
			countdown.value--
			if (countdown.value <= 0) {
				stopTimer()
			}
		}, 1000) as unknown as NodeJS.Timeout
	}



	const handleCode = async () => {
		if (countdown.value > 0 && timer.value) return
		// let res = await getCode(form.value.phonenumber)
		// if(res){
		// 	countdown.value = 60
		// 	startTimer()
		// }
	}

	const handleSure = () => {
		formRef.value.validate(async (valid : boolean) => {
			if (valid) {
				let bankform = {
					bankCardNumber: form.value.idcard,
					bankCode: form.value.bankValue,
					accountOpeningBank: form.value.openingBank,
					cardholder: form.value.name,
					reservePhoneNumber: form.value.tel
				}
				let res = await addBank(Number(form.value.tel), bankform)
				if(res.code == 200){
					uni.showToast({ title: '绑定银行卡成功' })
					formRef.value.resetFields()
					uni.navigateBack({
						delta: 1,
						success: () => {
							uni.$emit('getBank', {data: true})
						}
					})
				}
			} else {
				uni.showToast({
					icon: "none",
					title: "请检查信息是否完整",
				})
			}
		});
	}

	onMounted(() => {
		formRef.value.setRules(rules.value);
	});

	onUnmounted(() => {
		stopTimer()
	})
</script>

<style lang="scss" scoped>
	@import '@/style/style.scss';

	:deep(.u-form-item__message) {
		display: flex;
		justify-content: flex-end;
	}

	.box {
		height: 100%;
		min-height: 100vh;
		background: #F5F5F6;

		.container {
			.top {
				.title {
					color: #333333;
					font-weight: bold;
					font-family: PingFang SC;
				}

				.small_desc {
					color: #666666;
					font-weight: 500;
					font-family: PingFang SC;
				}
			}

			.common_item {
				background: #FFFFFF;
				border-radius: 10rpx;

				.idcard_input {
					display: flex;
					justify-content: flex-end;

					.default {
						color: rgb(192, 196, 204);
					}
				}

				.photo_icon {
					width: 38rpx;
					height: 38rpx;
				}

				.code_text {
					color: #3C51F2;
				}
			}

			.sure_btn {
				background: #3C51F2;
				height: 100rpx;
			}
		}

	}
</style>